package cz.acies.data.persist;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class ModelObject implements Serializable
{
	private static final long serialVersionUID = 1702254186170932573L;
	
	public String ID_PREFIX = "";
	
	protected String id;
	protected Map<String, Object> data = new HashMap<String, Object>();
	
	private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

	public ModelObject() {}

	public ModelObject(String id, Map<String, Object> data) {
		this.id = id;
		if (data != null) {
			this.data = data;
		} else {
			this.data = new HashMap<String, Object>();		
		}
	}

	// -----  ----------------------------------------------------------------- 
	
	public String getId() {
		return id;
	}

	public boolean hasId() {
		return (id != null && id.length() > 0);
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public Map<String, Object> getData() {
		return data;
	}

	public Object getData(String key) {
		return data.get(key);
	}

	public void setData(String key, Object value) {
		data.put(key, value);
	}
	
	public void removeData(String key) {
		data.remove(key);
	}

	// -----  -----------------------------------------------------------------

	protected Object setValidObject(Object obj, Object value, String key) {
		firePropertyChange(key, obj, obj = value);
		getData().put(key, value);
		return obj;
	}

	protected Object getValidObject(Object obj, String key) {
		if (obj == null) obj = getData().get(key);
		return obj;
	}

	// -----  -----------------------------------------------------------------
	
	public final void addPropertyChangeListener(PropertyChangeListener listener) {
		propertyChangeSupport.addPropertyChangeListener(listener);
	}

	public final void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
		propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
	}

	public final void removePropertyChangeListener(PropertyChangeListener listener) {
		propertyChangeSupport.removePropertyChangeListener(listener);
	}

	public final void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
		propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
	}

	final void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
		propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
	}
}
